<?php

class PostModel extends RelationModel {
	
	public $condition = array();
	
	protected $_link = array(
		'tag' => array(
			'mapping_type' => MANY_TO_MANY, //更新是删除之前的数据后重新写入
			'mapping_order' => 'count DESC',
		),
		
	);
	
    function getOne($postId) {
    	$result = $this->getList(array('id'=>$postId), '');
    	return $result[0];
    }
    
    //列表
    function getList($condition = array(), $limit = 15, $order = '') {
    	//$order='b.count';
    	$list = $this->relation(true)->where($condition)->order($order)->limit($limit)->select();
    	return $list;
    }
    
    function getListByTag($tagId, $limit = 15) { //TODO 联合检索
    	$condition = array();
    	$dbPre = C('DB_PREFIX');
    	$list = $this->join('INNER JOIN '.$dbPre.'post_tag ON '.$dbPre.'post_tag.post_id = '.$dbPre.'post.id')->group($dbPre.'post_tag.post_id')->select();
    	$PostTag = D('PostTag');
    	foreach($list as &$eachRow) {
    		$eachRow['tags'] = $PostTag->getTags($eachRow['id']);
    	}
    	return $list;
    }
    
    function addPost() {
    	
    	$this->create();
    	$postId = $this->add();
    	
    	$tagArr; //TODO 获取tag数组
    	
    	$Tag = D('Tag');
    	foreach($tagArr as $eachTag) {
    		$eachTagId = $Tag->addTag($eachTag);
    		if($eachTagId) {
    			$PostTag->addPostTag($postId, $eachTagId);
    		}
    	}
    	return $postId;
    }
    
    function delPost($postId) {
    	$result = $this->delete($postId);
    	if(!$result) {
    		return $result;
    	}
    	$PostTag = D('PostTag');
    	$tagIds = $PostTag->getTagIds($postId);
    	$PostTag->delByPostId($postId);
    	$Tag = D('Tag');
    	$Tag->tagDec($tagIds);
    	return $result;
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}